import store from '@/store'
import axios from 'axios'
import router from '@/router'
import { Message } from 'element-ui'

const service = axios.create({
  baseURL: '/api',
  timeout: 20000
})
service.interceptors.request.use(config => {
  if (store.getters.token) {
    config.headers.Authorization = `Bearer ${store.getters.token}`
  }
  return config
}, error => Promise.reject(error)
)

service.interceptors.response.use((response) => {
  if (response.data instanceof Blob) return response.data
  const { data, success, message } = response.data
  if (success) {
    return data
  }
  Message.error(message)
  return Promise.reject(new Error(message))
}, async error => {
  if (error.response.status === 401) {
    await store.dispatch('user/logout')
    router.push('/login')
    Message.error('用户信息超时')
  } else {
    Message.error(error.message)
  }
  return Promise.reject(error)
})
export default service
